<template>
  <div v-loading="pageLoading" element-loading-text="数据正在读取中，请稍候！" element-loading-spinner="el-icon-loading" class="analysis-container">
    <el-form :inline="true" class="search-box">
      <!-- <el-form-item label="单米选取">
        <el-input v-model="q.user" placeholder="单米选取" @keyup.enter.native="load" />
      </el-form-item> -->
      <el-form-item label="单米选取">
        <el-select v-model="q.meterVal" placeholder="单米选取">
          <el-option v-for="item in deepList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 80px;" :disabled="!q.meterVal" @click="getSingleData">确定</el-button>
        <!-- <el-button type="default" icon="el-icon-refresh" @click="resetSearch">重置</el-button> -->
      </el-form-item>
    </el-form>
    <div class="main-box">
      <div class="main-body">
        <div class="main-body-flex">
          <!-- <span v-for="i in 10" :key="i" class="kedu" :style="{'top': i*10+'%'}"></span> -->
          <div class="scale-box">
            <div class="scale-tit">0m</div>
            <span v-for="i in 10" :key="i">{{ i/10 }}m</span>
          </div>
          <div class="result-box">
            <div class="result-item">
              <div class="title">三维体数据</div>
              <div ref="scaleBody" v-loading="loading4" class="body">
                <vue3dLoader v-if="scaleHeight" :height="scaleHeight" :file-path="filePath" :controls-options="{enableZoom:false}" background-color="#efefef" :camera-position="{x:0, y:90, z:0}" point-light-follow-camera enable-axes-helper></vue3dLoader>
              </div>
            </div>
            <div class="result-item">
              <div class="title">外切面</div>
              <div v-loading="loading3" class="body">
                <div class="line-green" :style="{'top': heightEXT}">{{ extDouble }}</div>
                <canvas id="canvasEXT" @click="canvasEXTClick"></canvas>
              </div>
            </div>
            <div class="result-item">
              <div class="title">X-Z切片</div>
              <div v-loading="loading2" class="body">
                <canvas id="canvasXZ"></canvas>
              </div>
            </div>
            <!-- <div class="result-item">
              <div class="title">岩性分类</div>
              <div class="body">
                <img src="@/assets/images/image04.jpg">
              </div>
            </div> -->
            <div class="result-item">
              <div class="title">有效原子序数/密度</div>
              <div id="echarts1" v-loading="loading6" class="body"></div>
            </div>
          </div>
        </div>
      </div>
      <div class="main-right">
        <el-form ref="filterForm" :model="filter" :rules="filterFormRules" class="right-form">
          <el-form-item label="井号#" prop="wellNum">
            <el-input v-model="filter.wellNum" placeholder="请输入井号" />
          </el-form-item>
          <el-divider>多米连续选取</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="顶深(m)" prop="topDepth">
                <el-input-number v-model="filter.topDepth" :min="0" :max="filter.bottomDepth" :step="1" placeholder="顶深(m)"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="底深(m)" prop="bottomDepth">
                <el-input-number v-model="filter.bottomDepth" :min="filter.topDepth" :step="1" placeholder="底深(m)"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button type="primary" style="width: 100%;" @click="setOptions">确定</el-button>
          </el-form-item>
        </el-form>
        <div class="result-box">
          <div class="result-item">
            <div class="title">X-Y切片</div>
            <div class="body">
              <div v-loading="loading1" class="body-inner">
                <div class="line-green" :style="{'top': heightXT}">{{ xyDouble }}</div>
                <canvas id="canvasXY" ref="canvasXY" :height="canvasXYHeight" @click="canvasXYClick"></canvas>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { vue3dLoader } from "vue-3d-loader";
import echarts from 'echarts'
import { mapGetters } from 'vuex'
import { drawGrayscaleImageFromArray, transScatter } from '@/utils'

import { getPageOneOp } from "@/api/analysis";

export default {
  name: 'Exhibition',
  components: {
    vue3dLoader
  },
  data() {
    return {
      pageLoading: false,
      loading: false,
      loading1: false,
      loading2: false,
      loading3: false,
      loading4: false,
      loading6: false,
      heightEXT: '50%',
      heightXT: '50%',
      scaleHeight: 0,
      canvasXYHeight: 0,
      isEXTReady: false,
      isXYReady: false,
      chart1: null,
      filter: {
        wellNum: '1',
        topDepth: 4423,
        bottomDepth: 4424
      },
      filePath: '',
      extDouble: 0.5,
      xyDouble: 0.5,
      q: {
        meterVal: undefined
      },
      lights: [
        {
          type: "AmbientLight",
          color: "#000000"
        },
        {
          type: "DirectionalLight",
          position: { x: 100, y: 10, z: 100 },
          color: "green",
          intensity: 0.8
        },
        {
          type: "PointLight",
          color: "#000000",
          position: { x: 200, y: -200, z: 100 },
          intensity: 1
        },
        {
          type: "HemisphereLight",
          skyColor: "#00FF00",
          groundColor: "#000000",
          position: { x: 200, y: -200, z: 100 }
        }
      ],
      deepList: [],
      filterFormRules: {
        topDepth: [
          { required: true, message: '请输入顶深', trigger: ['blur', 'change'] }
        ],
        bottomDepth: [
          { required: true, message: '请输入底深', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['app'])
  },
  created() {
  },
  mounted() {
    this.$nextTick(() => {
      this.scaleHeight = this.$refs.scaleBody.offsetHeight;
      this.canvasXYHeight = this.$refs.canvasXY.offsetWidth;
      console.log(this.scaleHeight);
    });
  },
  methods: {
    setOptions() {
      this.$refs['filterForm'].validate((valid) => {
        if (valid) {
          const optList = [];
          const lowEnd = Math.floor(Number(this.filter.topDepth)); // 向下取整
          const highEnd = Math.floor(Number(this.filter.bottomDepth)); // 向上取整
          for (var i = lowEnd; i < highEnd; i++) {
            optList.push({
              label: `${i}米~${i + 1}米`,
              value: i
            });
          }
          this.deepList = optList;
          this.q.meterVal = optList[0].value;

          this.getReadyData();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 查询数据是否准备完成
    getReadyData() {
      this.pageLoading = true;
      this.isEXTReady = false;
      this.isXYReady = false;
      const q = {
        user: 'anyone',
        opType: 0,
        meter: [this.filter.topDepth, this.filter.bottomDepth]
      }
      getPageOneOp(q).then(res => {
        if (res && res.message) {
          this.pageLoading = false;
          this.searchSubmit(); // 已完成调用获取切片数据
        } else {
          setTimeout(() => {
            this.getReadyData(); // 未完成继续轮询
          }, 3000);
        }
      }).catch((error) => {
        console.log(error);
        this.pageLoading = false;
      });
    },
    getSingleData() { // 更改当前操作对应的单个米数
      this.pageLoading = true;
      this.isEXTReady = false;
      this.isXYReady = false;

      const q = {
        user: 'anyone',
        opType: 5,
        meter: [this.q.meterVal, this.q.meterVal + 1]
      }
      console.log(q);
      getPageOneOp(q).then(res => {
        if (res && res.message) {
          this.pageLoading = false;
          this.searchSubmit(); // 已完成调用获取切片数据
        } else {
          setTimeout(() => {
            this.getSingleData(); // 未完成继续轮询
          }, 3000);
        }
      }).catch((error) => {
        console.log(error);
        this.pageLoading = false;
      });
    },
    searchSubmit() {
      this.heightEXT = '50%';
      this.heightXT = '50%';
      this.extDouble = 0.5;
      this.xyDouble = 0.5;
      this.getList(1);
      this.getList(2);
      this.getList(3);
      this.getList(4);
      this.getList(6);
    },
    getList(opType) {
      this['loading' + opType] = true;
      const q = {
        user: 'anyone',
        opType
      };
      if (opType === 1 || opType === 2) { // X-Y切片 和 X-Z切片
        q.Double = opType === 1 ? this.extDouble : this.xyDouble;
      }
      console.log(q);
      getPageOneOp(q).then(res => {
        if (res && res.message) {
          if (opType === 1) {
            this.isXYReady = true;
            drawGrayscaleImageFromArray(res.pic, 'canvasXY'); // X-Y切片
          } else if (opType === 2) {
            drawGrayscaleImageFromArray(res.pic, 'canvasXZ'); // X-Z切片
          } else if (opType === 3) {
            this.isEXTReady = true;
            drawGrayscaleImageFromArray(res.pic, 'canvasEXT'); // 外切面
          } else if (opType === 4) {
            console.log(res.model_path);
            this.filePath = `http://1.13.3.248${res.model_path}`;
            // this.filePath = `/ssss.obj`;
          } else if (opType === 6) {
            console.log(res.data);
            const data = res.data;
            // const data = {
            //   'Pe': [3.036598186, 2.967032715, 2.918064182, 2.912824497, 2.897535477],
            //   '密度': [2.606923077, 2.599903846, 2.596923077, 2.597788462, 2.6],
            //   '深度': [4955.139, 4955.14, 4955.141, 4955.142, 4955.143]
            // }
            console.log(transScatter(data));
            this.initChart1(transScatter(data));
          }
          this['loading' + opType] = false;
        } else {
          if (res && opType === 4) {
            setTimeout(() => {
              this.getList(4); // 未完成继续轮询
            }, 3000);
          }
        }
      }).catch((error) => {
        console.log(error);
        this['loading' + opType] = false;
      });
    },
    canvasEXTClick(e) {
      if (this.isEXTReady) {
        const canvasHeight = e.target.clientHeight;
        this.extDouble = e.offsetY / canvasHeight;
        this.heightEXT = this.extDouble * 100 + '%';
        this.getList(1);
        // console.log(e.target.clientHeight);
        // console.log(this.heightEXT / canvasHeight);
      }
    },
    canvasXYClick(e) {
      if (this.isXYReady) {
        const canvasHeight = e.target.clientHeight;
        this.xyDouble = e.offsetY / canvasHeight;
        this.heightXT = this.xyDouble * 100 + '%';
        this.getList(2);
        // console.log(e.target.clientHeight);
        // console.log(this.heightEXT / canvasHeight);
      }
    },
    initChart1(data) {
      this.chart1 = echarts.init(document.getElementById("echarts1"));
      this.chart1.setOption({
        // title: {
        //   text: 'Male and female height and weight distribution'
        // },
        grid: {
          left: '3%',
          right: '7%',
          bottom: '7%',
          top: '3%',
          containLabel: true
        },
        tooltip: {
          // trigger: 'axis',
          showDelay: 0,
          formatter: function (params) {
            if (params.value.length > 1) {
              return (
                params.seriesName +
                ' :<br/>' +
                params.value[0]
              );
            } else {
              return (
                params.seriesName +
                ' :<br/>' +
                params.value
              );
            }
          },
          axisPointer: {
            show: true,
            type: 'cross',
            lineStyle: {
              type: 'dashed',
              width: 1
            }
          }
        },
        brush: {},
        toolbox: {
          show: false
        },
        legend: {
          data: ['Pe', '密度'],
          left: 'center',
          bottom: 10
        },
        xAxis: [
          {
            type: 'value',
            scale: true,
            axisLabel: {
              formatter: '{value}'
            },
            splitLine: {
              show: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            scale: true,
            min: this.q.meterVal,
            max: this.q.meterVal + 1,
            inverse: true,
            axisLabel: {
              formatter: '{value}'
            },
            splitLine: {
              show: true
            }
          }
        ],
        series: [
          {
            name: 'Pe',
            type: 'scatter',
            emphasis: {
              focus: 'series'
            },
            symbolSize: 5,
            // prettier-ignore
            data: data['Pe']
          },
          {
            name: '密度',
            type: 'scatter',
            emphasis: {
              focus: 'series'
            },
            symbolSize: 5,
            // prettier-ignore
            data: data['密度']
          }
        ]
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.analysis-container {
  position: relative;
  width: 100%;
  height: calc(100vh - 50px);
  padding: 10px;
  display: flex;
  flex-direction: column;
}
.search-box {
  padding: 10px 10px 0;
  background-color: #fff;
  .el-form-item {
    margin-bottom: 10px;
  }
}
.main-box {
  flex: 1;
  margin-top: 10px;
  overflow: hidden;
  display: flex;
  .main-body {
    background-color: #fff;
    flex: 1;
    display: flex;
    padding: 10px;
    .main-body-flex {
      position: relative;
      display: flex;
      flex: 1;
    }
    .kedu {
      position: absolute;
      left: 0;
      right: 0;
      border: 1px dashed rgba(4, 255, 0, 0.3);
    }
  }
  .main-right {
    max-width: 300px;
    margin-left: 10px;
    background-color: #fff;
    padding: 10px;
    display: flex;
    flex-direction: column;
  }
}
.scale-box {
  margin-top: 20px;
  position: relative;
  display: flex;
  flex-direction: column;
  border-left: 2px solid #000;
  line-height: 1;
  .scale-tit {
    position: absolute;
    left: 0;
    top: 0;
    font-size: 12px;
    display: flex;
    align-items: flex-start;
    border-top: 1px solid #000;
    padding-left: 2px;
    padding-top: 2px;
    min-width: 29px;
  }
  span {
    flex: 1;
    display: flex;
    align-items: flex-end;
    font-size: 12px;
    border-bottom: 1px solid #000;
    padding-left: 2px;
    min-width: 29px;
  }
}
.result-box {
  display: flex;
  flex: 1;
  .result-item {
    margin: 0 5px;
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .title {
      text-align: center;
      font-size: 14px;
      height: 20px;
      line-height: 20px;
    }
    .body {
      position: relative;
      flex: 1;
      overflow: hidden;
      .line-green {
        position: absolute;
        left: 0;
        right: 0;
        z-index: 10;
        border-top: 1px solid #00fe03;
        color: #00fe03;
        font-size: 12px;
        padding-top: 2px;
      }
    }
    .body-inner {
      position: relative;
    }
    canvas {
      width: 100%;
      height: 100%;
      background-color: #efefef;
    }
    img {
      max-width: 100%;
      height: 100%;
    }
  }
}
#echarts1{
  background-color: #efefef;
}
.right-form {
  .el-form-item {
    // margin-bottom: 10px;
  }
  .el-divider--horizontal {
    // margin-top: 20px;
    margin-bottom: 20px;
  }
}
</style>
